package logic_user_menu

import (
	v1 "Sailor/app/Sailor-console-server/api/api_user_menu/v1"
	"Sailor/app/Sailor-console-server/internal/consts"
	"Sailor/app/Sailor-console-server/internal/dao"
	"Sailor/app/Sailor-console-server/internal/model/entity"
	"Sailor/app/Sailor-console-server/utility/utility_menu"
	"context"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
)

func (s *sUserMenu) LogicUserMenu(ctx context.Context, req *v1.UserMenuReq) (res *v1.UserMenuRes, err error) {

	var userInfo entity.SysUser
	err = g.RequestFromCtx(ctx).GetCtxVar(consts.CtxUserInfoKey).Scan(&userInfo)
	if err != nil {
		g.Log().Error(ctx, err)
		return nil, gerror.New("获取用户菜单失败")
	}

	menuIds, err := dao.SysRoleMenu.Ctx(ctx).Where(dao.SysRoleMenu.Columns().RoleCode, userInfo.UserRole).Fields(dao.SysRoleMenu.Columns().MenuId).Array()
	if err != nil {
		g.Log().Error(ctx, err)
		return nil, gerror.New("获取菜单失败")
	}

	var menus []entity.SysMenu
	err = dao.SysMenu.Ctx(ctx).With(entity.SysMenu{}).
		Where(dao.SysMenu.Columns().MenuParentId, "").
		Where(dao.SysMenu.Columns().Uuid, menuIds).
		OrderAsc(dao.SysMenu.Columns().MenuSort).Scan(&menus)
	if err != nil {
		g.Log().Error(ctx, err)
		return nil, gerror.New("获取菜单失败")
	}

	var PermissionsArray []string
	collectButtonPermissions(menus, &PermissionsArray)

	return &v1.UserMenuRes{
		Menu:        utility_menu.MenuFormat(menus),
		Permissions: gconv.Strings(PermissionsArray),
	}, nil
}

// 辅助函数：递归地收集按钮权限
func collectButtonPermissions(menus []entity.SysMenu, permissions *[]string) {
	for _, v := range menus {
		if v.Type == "button" {
			*permissions = append(*permissions, v.Name)
		}
		if v.Children != nil {
			collectButtonPermissions(v.Children, permissions)
		}
	}
}
